//
//  NWloginViewController.m
//  海口人民医院
//
//  Created by God on 16/4/25.
//  Copyright © 2016年 N-wei. All rights reserved.
//

#import "NWloginViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "JPUSHService.h"
#import "UIView+GM.h"
#import "GMSystemTool.h"
#import "GMLoginViewModel.h"
#import "GMWebViewController.h"

typedef void (^GMSignInResponse)(BOOL);

@interface NWloginViewController (){
    MBProgressHUD *HUD;
}


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *loginTopC;
@property (weak, nonatomic) IBOutlet UITextField *userNameLab;
@property (weak, nonatomic) IBOutlet UITextField *passwordLab;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nameHeightConnstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *passwordHeightConnstraint;

@property (weak, nonatomic) IBOutlet UIButton *selectAdressBtn;
@property (weak, nonatomic) IBOutlet UITextField *addressF;
@property (weak, nonatomic) IBOutlet UIView *addressLine;
@property (weak, nonatomic) IBOutlet UILabel *addressHintLab;
@property (weak, nonatomic) IBOutlet UILabel *companyLab;
@property (weak, nonatomic) IBOutlet UIImageView *logoImg;

@end


@implementation NWloginViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    //1 check network
    [GMSystemTool gm_reachability];
    
    //2 setup ui
    [self  setupUI];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //1 setup action
    [self setupAction];
    //    [self testJspatch];
}





/**
 * setup ui
 */
-(void)setupUI{
    
    //setup deafaul  username password
    self.userNameLab.text = [GMDataHandleTool read:GM_USERNAME];
    self.passwordLab.text = [GMDataHandleTool read:GM_PASSWORD];
    
    
    //2 Set company info  [logo/company name]
    self.companyLab.text =  [GMDataHandleTool read:ZBOMC_USER_COMPANY];
    NSString *imageURL= [NSString stringWithFormat:@"http://zbomc.com:8090%@",[GMDataHandleTool read:ZBOMC_USER_LOGO]];
    [self.logoImg sd_setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:[UIImage imageNamed:@"logo"]];
    self.logoImg.contentMode = UIViewContentModeScaleAspectFit;
    
    
    //3 judge is have username & password
    if (self.userNameLab.text.length>0 && self.passwordLab.text.length>0) {
        self.loginButton.enabled = YES;
        self.loginButton.backgroundColor =[UIColor colorWithHexString:@"#10D45F"];
    }
    
    
    //setup corner
    self.loginButton.layer.cornerRadius = 4;
    self.loginButton.layer.masksToBounds = YES;
    
    //setup placehoder color
    [_userNameLab setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_passwordLab setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_addressF setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    
}




/**
 * setup action
 */
-(void)setupAction{
    @weakify(self)
    //next
    [[RACSignal combineLatest:@[self.userNameLab.rac_textSignal,
                                self.passwordLab.rac_textSignal
                                ]
                       reduce:^(NSString *text1, NSString *text2){
                           return @(text1.length && text2.length);
                       }] subscribeNext:^(id x) {
                           @strongify(self)
                           self.loginButton.enabled =[x boolValue];
                           self.loginButton.backgroundColor = [x boolValue] == NO?[UIColor lightGrayColor]:[UIColor colorWithHexString:@"#10D45F"];
                       }];
    
    
    //1
    [[self.selectAdressBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
        
        [self gm_selectAdressAction];
    }];
    
    
    //2 submit
    [[self.loginButton rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(id x) {
        
        [self gm_loginAction];
    }];
    
}


/**
 *	login action block
 */
-(void)gm_loginAction{
    
    //1 save value
    [GMDataHandleTool save:GM_USERNAME data:_userNameLab.text];
    [GMDataHandleTool save:GM_PASSWORD data:_passwordLab.text];
    
    if (self.selectAdressBtn.selected)
    [GMDataHandleTool save:GM_ADDRESS data:_addressF.text];
    else
    [GMDataHandleTool remove:GM_ADDRESS];
    
    
    
    //2 login
    HUD = [MBProgressHUD showMessage:@"登录中..."];
    
    
    [GMLoginViewModel login:nil success:^(id respones) {
        [HUD  hideAnimated:YES];
        
        if ([respones[@"result"] isEqualToString:@"success"]) {
            
            id jsonObj = respones[@"data"][@"customer"];
            NSString *jpustTagStr = [NSString stringWithFormat:@"%@",jsonObj[@"id"]];
            
            //1.JPush
            [JPUSHService setTags:[NSSet setWithObject:jpustTagStr] callbackSelector:nil object:self];
            
            //2.Sava Base info
            [GMDataHandleTool save:ZBOMC_USER_COMPANY data:jsonObj[@"company"]];
            [GMDataHandleTool save:ZBOMC_USER_LOGO data:jsonObj[@"description"]];
            
            //3.Jump application
            [self.navigationController pushViewController:[[GMWebViewController alloc]init] animated:YES];
        }else {
            
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"警告" message:@"账户或密码输入错误" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alertView show];
        }
        
    } failure:^(NSError *error) {
        [HUD  hideAnimated:YES];
    }];
    
}



/**
 *	Select default Adress option
 */
-(void)gm_selectAdressAction{
    /*
     1. judge button select
     2. if selected  show  addressF addressL
     3. if unselected hint  addressF addressL
     4 如果选择的是输入地址，则需要在提交的时候保存URL
     */
    self.selectAdressBtn.selected = !self.selectAdressBtn.selected;
    
    LxDBAnyVar(self.selectAdressBtn.selected);
    if (self.selectAdressBtn.selected) {
        self.addressF.hidden = NO;
        self.addressLine.hidden = NO;
        self.addressHintLab.text = @"格式例如zbomc.com";
        [self.selectAdressBtn setImage:[UIImage imageNamed:@"unchecked"] forState:UIControlStateNormal];
        
        
        // 如果是输入地址，则必须输入
        @weakify(self)
        [[RACSignal combineLatest:@[self.addressF.rac_textSignal
                                    ]
                           reduce:^(NSString *text1){
                               return @(text1.length);
                           }] subscribeNext:^(id x) {
                               @strongify(self)
                               self.loginButton.enabled =[x boolValue];
                               self.loginButton.backgroundColor = [x boolValue] == NO?[UIColor lightGrayColor]:[UIColor colorWithHexString:@"#10D45F"];
                           }];
    }else{
        self.addressF.hidden = YES;
        self.addressLine.hidden = YES;
        self.addressHintLab.text = @"用默认地址";
        
        [self.selectAdressBtn setImage:[UIImage imageNamed:@"checked"] forState:UIControlStateNormal];
    }
}



-(void)testJspatch{
    [MBProgressHUD showMessage:@"test select * from JSpatch"];
}
@end
